import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { useAuth } from '../context/AuthContext';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';
import { FaUserPlus, FaCheck, FaTimes } from 'react-icons/fa';
import '../styles/UserManagement.css';

const UserManagement = () => {
  const { user } = useAuth();
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [success, setSuccess] = useState('');
  const [showAddForm, setShowAddForm] = useState(false);

  // 获取用户列表
  const fetchUsers = async () => {
    try {
      setLoading(true);
      const res = await axios.get('/api/auth/users');
      setUsers(res.data);
      setError(null);
    } catch (err) {
      console.error('获取用户列表失败:', err);
      setError(err.response?.data?.message || '获取用户列表失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchUsers();
  }, []);

  // 处理用户状态切换
  const handleToggleStatus = async (userId, currentStatus) => {
    try {
      await axios.patch(`/api/auth/users/${userId}/status`, {
        active: !currentStatus
      });
      
      // 刷新用户列表
      await fetchUsers();
      
      setSuccess(`用户状态已更改为${!currentStatus ? '启用' : '禁用'}`);
      setTimeout(() => setSuccess(''), 3000);
    } catch (err) {
      console.error('更改用户状态失败:', err);
      setError(err.response?.data?.message || '更改用户状态失败');
    }
  };

  // 处理添加用户
  const handleAddUser = async (values, { resetForm, setSubmitting }) => {
    try {
      await axios.post('/api/auth/register', values);
      
      // 刷新用户列表
      await fetchUsers();
      
      // 重置表单并关闭
      resetForm();
      setShowAddForm(false);
      setSuccess('新用户添加成功');
      setTimeout(() => setSuccess(''), 3000);
    } catch (err) {
      console.error('添加用户失败:', err);
      setError(err.response?.data?.message || '添加用户失败');
    } finally {
      setSubmitting(false);
    }
  };

  // 验证规则
  const validationSchema = Yup.object({
    username: Yup.string().required('用户名为必填项'),
    email: Yup.string().email('请输入有效的邮箱地址').required('邮箱为必填项'),
    password: Yup.string().min(6, '密码至少需要6个字符').required('密码为必填项'),
    role: Yup.string().required('角色为必填项')
  });

  // 获取角色标签
  const getRoleLabel = (role) => {
    const roleMap = {
      'admin': '管理员',
      'user': '用户',
      'viewer': '查看者'
    };
    
    return roleMap[role] || role;
  };

  if (loading && users.length === 0) {
    return <div className="loading">加载中...</div>;
  }

  if (!user || user.role !== 'admin') {
    return <div className="error-message">您没有权限访问此页面</div>;
  }

  return (
    <div className="user-management-container">
      <div className="page-header">
        <h1>用户管理</h1>
        <button 
          className="add-button"
          onClick={() => setShowAddForm(!showAddForm)}
        >
          <FaUserPlus /> {showAddForm ? '取消添加' : '添加用户'}
        </button>
      </div>

      {error && <div className="error-message">{error}</div>}
      {success && <div className="success-message">{success}</div>}

      {/* 添加用户表单 */}
      {showAddForm && (
        <div className="add-user-form">
          <h2>添加新用户</h2>
          <Formik
            initialValues={{
              username: '',
              email: '',
              password: '',
              role: 'viewer'
            }}
            validationSchema={validationSchema}
            onSubmit={handleAddUser}
          >
            {({ isSubmitting }) => (
              <Form>
                <div className="form-row">
                  <div className="form-group">
                    <label htmlFor="username">用户名*</label>
                    <Field type="text" id="username" name="username" />
                    <ErrorMessage name="username" component="div" className="error" />
                  </div>
                  
                  <div className="form-group">
                    <label htmlFor="email">邮箱*</label>
                    <Field type="email" id="email" name="email" />
                    <ErrorMessage name="email" component="div" className="error" />
                  </div>
                </div>
                
                <div className="form-row">
                  <div className="form-group">
                    <label htmlFor="password">密码*</label>
                    <Field type="password" id="password" name="password" />
                    <ErrorMessage name="password" component="div" className="error" />
                  </div>
                  
                  <div className="form-group">
                    <label htmlFor="role">角色*</label>
                    <Field as="select" id="role" name="role">
                      <option value="admin">管理员</option>
                      <option value="user">用户</option>
                      <option value="viewer">查看者</option>
                    </Field>
                    <ErrorMessage name="role" component="div" className="error" />
                  </div>
                </div>
                
                <div className="form-actions">
                  <button type="submit" disabled={isSubmitting}>
                    {isSubmitting ? '提交中...' : '添加用户'}
                  </button>
                </div>
              </Form>
            )}
          </Formik>
        </div>
      )}

      {/* 用户列表 */}
      {users.length > 0 ? (
        <div className="users-table-container">
          <table className="users-table">
            <thead>
              <tr>
                <th>用户名</th>
                <th>邮箱</th>
                <th>角色</th>
                <th>状态</th>
                <th>最后登录</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              {users.map(u => (
                <tr key={u._id} className={!u.active ? 'inactive-row' : ''}>
                  <td>{u.username}</td>
                  <td>{u.email}</td>
                  <td>
                    <span className={`role-badge role-${u.role}`}>
                      {getRoleLabel(u.role)}
                    </span>
                  </td>
                  <td>
                    <span className={`status-badge ${u.active ? 'active' : 'inactive'}`}>
                      {u.active ? '已启用' : '已禁用'}
                    </span>
                  </td>
                  <td>{u.lastLogin ? new Date(u.lastLogin).toLocaleString() : '从未登录'}</td>
                  <td>
                    {u._id !== user._id ? (
                      <button 
                        onClick={() => handleToggleStatus(u._id, u.active)}
                        className={`status-toggle ${u.active ? 'disable' : 'enable'}`}
                        title={u.active ? '禁用账户' : '启用账户'}
                      >
                        {u.active ? <FaTimes /> : <FaCheck />}
                        {u.active ? '禁用' : '启用'}
                      </button>
                    ) : (
                      <span className="self-message">当前账户</span>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : (
        <div className="no-data">
          暂无用户数据
        </div>
      )}
    </div>
  );
};

export default UserManagement; 